package com.t3rik.mes.emp.controller;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.t3rik.common.utils.DateUtils;
import com.t3rik.mes.emp.domain.EmpSalary;
import com.t3rik.mes.emp.service.IEmpAttendanceRecordService;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.t3rik.common.annotation.Log;
import com.t3rik.common.core.controller.BaseController;
import com.t3rik.common.core.domain.AjaxResult;
import com.t3rik.common.utils.StringUtils;
import com.t3rik.common.enums.BusinessType;
import com.t3rik.mes.emp.service.IEmpSalaryService;
import com.t3rik.common.utils.poi.ExcelUtil;
import com.t3rik.common.core.page.TableDataInfo;

import javax.swing.text.html.Option;

/**
 * 工资总表Controller
 *
 * @author ykh
 * @date 2025-02-19
 */
@RestController
@RequestMapping("/hrm/salary")
public class EmpSalaryController extends BaseController {
    @Autowired
    private IEmpSalaryService empSalaryService;

    /**
     * 查询工资总表列表
     */
//    @PreAuthorize("@ss.hasPermi('hrm:salary:list')")
//    @GetMapping("/list")
//    public TableDataInfo list(EmpSalary empSalary) {
//        // 获取查询条件
//        LambdaQueryWrapper<EmpSalary> queryWrapper = getQueryWrapper(empSalary);
//        // 组装分页
//        Page<EmpSalary> page = getMPPage(empSalary);
//        // 查询
//        this.empSalaryService.page(page, queryWrapper);
//        return getDataTableWithPage(page);
//    }

    /**
     * 查询工资总表列表
     */
    @PreAuthorize("@ss.hasPermi('hrm:salary:list')")
    @GetMapping("/list")
    public TableDataInfo listV2(EmpSalary empSalary) {
        if(Objects.isNull(empSalary.getYear())){
            TableDataInfo res = new TableDataInfo();
            res.setMsg("年份必传");
            return res;
        }
        // 获取查询条件
        LambdaQueryWrapper<EmpSalary> queryWrapper = getQueryWrapper(empSalary);
        // 组装分页
        Page<EmpSalary> page = getMPPage(empSalary);
        this.empSalaryService.page(page, queryWrapper);
        if(page.getRecords().isEmpty()) {
            return getDataTableWithPage(page);
        }
        List<EmpSalary> result = empSalaryService.computeSalary(page.getRecords());
        // 查询
        Page<EmpSalary> page1 = this.empSalaryService.page(page, queryWrapper);
        page1.setRecords(result);
        return getDataTableWithPage(page);
    }
    /**
     * 导出工资总表列表
     */
    @PreAuthorize("@ss.hasPermi('hrm:salary:export')")
    @Log(title = "工资总表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EmpSalary empSalary) {
        // 获取查询条件
        LambdaQueryWrapper<EmpSalary> queryWrapper = getQueryWrapper(empSalary);
        List<EmpSalary> list = this.empSalaryService.list(queryWrapper);
        List<EmpSalary> result = empSalaryService.computeSalary(list);
        ExcelUtil<EmpSalary> util = new ExcelUtil<EmpSalary>(EmpSalary. class);
        util.exportExcel(response, result, "工资总表数据");
    }

    /**
     * 获取工资总表详细信息
     */
    @PreAuthorize("@ss.hasPermi('hrm:salary:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(this.empSalaryService.getById(id));
    }

    /**
     * 新增工资总表
     */
    @PreAuthorize("@ss.hasPermi('hrm:salary:add')")
    @Log(title = "工资总表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EmpSalary empSalary) {
        return toAjax(this.empSalaryService.save(empSalary));
    }

    /**
     * 修改工资总表
     */
    @PreAuthorize("@ss.hasPermi('hrm:salary:edit')")
    @Log(title = "工资总表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EmpSalary empSalary) {
        EmpSalary record = empSalaryService.getById(empSalary.getId());
        //更改结算状态
        BigDecimal settledAmount = record.getSettledPrice().add(empSalary.getSettledPrice());
        if(settledAmount.compareTo(record.getFinalPrice()) > 0){
            return AjaxResult.error("结算金额大于最终工资，请检查");
        }
        record.setSettledPrice(settledAmount);
        record.setUnsettledPrice(record.getFinalPrice().subtract(settledAmount));
        record.setLastSettledTime(LocalDateTime.now().toString());
        if(settledAmount.compareTo(record.getFinalPrice()) == 0){
            record.setSettlementStatus(EmpSalary.SettlementStatusEnum.SETTLED.getCode());
        } else{
            record.setSettlementStatus(EmpSalary.SettlementStatusEnum.PART_SETTLED.getCode());
        }
        return toAjax(this.empSalaryService.updateById(record));
    }

    /**
     * 删除工资总表
     */
    @PreAuthorize("@ss.hasPermi('hrm:salary:remove')")
    @Log(title = "工资总表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(this.empSalaryService.removeByIds(ids));
    }

    /**
    * 获取查询条件
    */
    public LambdaQueryWrapper<EmpSalary> getQueryWrapper(EmpSalary empSalary) {
        String year = empSalary.getYear();
        LocalDate startTime = LocalDate.of(Integer.parseInt(year), 1, 1);
        LocalDate endTime = LocalDate.of(Integer.parseInt(year), 12, 31);
        LambdaQueryWrapper<EmpSalary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.between(EmpSalary::getYear, startTime, endTime);
        queryWrapper.like(StringUtils.isNotEmpty(empSalary.getUserName()), EmpSalary::getUserName, empSalary.getUserName());
        queryWrapper.eq(empSalary.getSettlementStatus() != null, EmpSalary::getSettlementStatus, empSalary.getSettlementStatus());
        // 默认创建时间倒序
        queryWrapper.orderByDesc(EmpSalary::getCreateTime);
        Map<String, Object> params = empSalary.getParams();
        queryWrapper.between(params.get("beginTime") != null && params.get("endTime") != null,EmpSalary::getCreateTime, params.get("beginTime"), params.get("endTime"));
        return queryWrapper;
    }
}
